import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { whiteList } from '@/pages/soaManage/abilitymanagement/utils';
import { ExpandedDataType } from '@/types/ability';
import { DownOutlined } from '@ant-design/icons';
import { useSetState } from 'ahooks';
import {
  Button,
  Card,
  Collapse,
  Form,
  FormInstance,
  Input,
  message,
  Select,
  Spin,
  Table,
  TableColumnsType,
  TableProps,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import { ExpandableConfig } from 'antd/es/table/interface';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import React, { PureComponent, useEffect, useRef, useState } from 'react';
const FormItem = Form.Item;
const FormList = Form.List;
const interfaceTypeEnum = [
  {
    label: 'R&R Method',
    value: 'R&R Method',
  },
  {
    label: 'F&F Method',
    value: 'F&F Method',
  },
  {
    label: 'Event',
    value: 'Event',
  },
  {
    label: 'Field/Setter',
    value: 'Field/Setter',
  },
  {
    label: 'Field/Getter',
    value: 'Field/Getter',
  },
  {
    label: 'Field/Notify',
    value: 'Field/Notify',
  },
];
const protocolTypeEnum = [
  {
    label: 'UDP',
    value: 'UDP',
  },
  {
    label: 'TCP',
    value: 'TCP',
  },
  {
    label: 'TCP/UDP',
    value: 'TCP/UDP',
  },
];
const parameterTypeEnum = [
  {
    label: 'IN',
    value: 'IN',
  },
  {
    label: 'OUT',
    value: 'OUT',
  },
];
const tableFormItemStyle = { marginBottom: 0 };
const serviceContentDefaultValue = {
  name: undefined,
  desc: undefined,
  type: undefined,
  flag: undefined,
  eventGroup: undefined,
  protocol: undefined,
  params: [
    {
      name: undefined,
      desc: undefined,
      parameter: undefined,
      dataType: undefined,
    },
  ],
};

interface State {
  dataTypeAllOpt: any[];
  loading: boolean;
}
const addServer: React.FC = (props: any) => {
  const formRef = useRef<FormInstance>();
  const { history } = props;
  const [state, setState] = useSetState<State>({
    dataTypeAllOpt: [],
    loading: false,
  });

  const formItemLayout = {
    labelCol: {
      style: { width: 100 },
    },
    wrapperCol: {
      span: 12,
    },
  };
  const getdataTypeAll = () => {
    const { dispatch } = props;
    dispatch({
      type: 'basicService/getDataWithRes',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/type/all',
      },
      callback: res => {
        if (res.statusCode === '0') {
          setState({
            dataTypeAllOpt: (res.data ?? []).map(t => ({ label: t.name, value: t.name })),
          });
        }
      },
    });
  };
  const getCloumns = ({ remove, add }, fields) => {
    const columns: ColumnsType<any> = [
      {
        title: '服务接口元素名称',
        dataIndex: 'name',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'name']}
              rules={[{ required: true, message: '请输入名称' }]}
            >
              <Input placeholder="请输入" maxLength={50} />
            </Form.Item>
          );
        },
      },

      {
        title: '服务接口元素描述',
        dataIndex: 'desc',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'desc']}
              rules={[{ required: false, message: '请输入' }]}
            >
              <Input placeholder="请输入" maxLength={50} />
            </Form.Item>
          );
        },
      },

      {
        title: '服务接口类型',
        dataIndex: 'type',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'type']}
              rules={[{ required: false, message: '请选择' }]}
            >
              <Select options={interfaceTypeEnum} />
            </Form.Item>
          );
        },
      },
      {
        title: '服务接口元素标识符',
        dataIndex: 'flag',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'flag']}
              rules={[{ required: false, message: '请输入' }]}
            >
              <Input placeholder="请输入" maxLength={50} />
            </Form.Item>
          );
        },
      },
      {
        title: '事件组',
        dataIndex: 'eventGroup',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'eventGroup']}
              rules={[{ required: false, message: '请输入' }]}
            >
              <Input placeholder="请输入" maxLength={50} />
            </Form.Item>
          );
        },
      },
      {
        title: '传输层协议',
        dataIndex: 'protocol',
        width: 150,
        render: (_, field) => {
          return (
            <Form.Item
              nostyle
              style={tableFormItemStyle}
              wrapperCol={{ span: 24 }}
              {...field}
              name={[field.name, 'protocol']}
              rules={[{ required: false, message: '请选择' }]}
            >
              <Select options={protocolTypeEnum} />
            </Form.Item>
          );
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 100,
        fixed: 'right',
        render: (text: any, field) => {
          return fields.length > 1 ? (
            <Button
              type="primary"
              onClick={() => {
                remove(field.name);
              }}
            >
              删除
            </Button>
          ) : null;
        },
      },
    ];
    return columns;
  };
  const onFinish = values => {
    const { dispatch, history } = props;
    setState({ loading: true });
    dispatch({
      type: 'basicService/postObjWithRes',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/service/add',
        ...values,
      },
      callback: res => {
        if (res.statusCode === '0') {
          message.success('添加成功');
          history.push('/soaManage/serviceManage/serviceLibrary?tab=0');
        } else if (whiteList.includes(res.statusCode)) {
          message.error(res.statusMessage);
        }
      },
    }).finally(() => setState({ loading: false }));
  };
  useEffect(() => {
    getdataTypeAll();
  }, []);

  const childTableRender: ExpandableConfig<any>['expandedRowRender'] = feild => {
    const getCloumns = ({ remove, add }, fields) => {
      const columns: ColumnsType<any> = [
        {
          title: ' ',
          dataIndex: 'add',
          render: (value, feild, index) => {
            return index === 0 ? (
              <Button type="primary" onClick={() => add(serviceContentDefaultValue.params[0])}>
                添加
              </Button>
            ) : null;
          },
        },
        {
          title: '参数名称',
          dataIndex: 'name',
          render: (_, field) => {
            return (
              <Form.Item
                nostyle
                style={tableFormItemStyle}
                wrapperCol={{ span: 24 }}
                {...field}
                name={[field.name, 'name']}
                rules={[{ required: false, message: '请输入' }]}
              >
                <Input placeholder="请输入" maxLength={50} />
              </Form.Item>
            );
          },
        },
        {
          title: '参数描述',
          dataIndex: 'desc',
          render: (_, field) => {
            return (
              <Form.Item
                nostyle
                style={tableFormItemStyle}
                wrapperCol={{ span: 24 }}
                {...field}
                name={[field.name, 'desc']}
                rules={[{ required: false, message: '请输入' }]}
              >
                <Input placeholder="请输入" maxLength={50} />
              </Form.Item>
            );
          },
        },
        {
          title: '参数发送方向',
          dataIndex: 'parameter',
          render: (_, field) => {
            return (
              <Form.Item
                nostyle
                style={tableFormItemStyle}
                wrapperCol={{ span: 24 }}
                {...field}
                name={[field.name, 'parameter']}
                rules={[{ required: false, message: '请选择' }]}
              >
                <Select options={parameterTypeEnum} />
              </Form.Item>
            );
          },
        },
        {
          title: '参考数据类型',
          dataIndex: 'dataType',
          render: (_, field) => {
            return (
              <Form.Item
                nostyle
                style={tableFormItemStyle}
                wrapperCol={{ span: 24 }}
                {...field}
                name={[field.name, 'dataType']}
                rules={[{ required: false, message: '请选择' }]}
              >
                <Select
                  optionLabelProp="label"
                  showSearch
                  allowClear
                  options={state.dataTypeAllOpt}
                />
              </Form.Item>
            );
          },
        },
        {
          title: ' ',
          dataIndex: '操作',
          width: 100,
          fixed: 'right',
          render: (text: any, field) => {
            return fields.length > 1 ? (
              <Button
                type="link"
                onClick={() => {
                  remove(field.name);
                }}
              >
                删除
              </Button>
            ) : null;
          },
        },
      ];
      return columns;
    };

    return (
      <FormList name={[feild.name, 'params']}>
        {(fields, { remove, add }) => {
          return (
            <>
              <Table
                size="small"
                rowKey="key"
                columns={getCloumns({ remove, add }, fields)}
                dataSource={fields}
                pagination={false}
              />
            </>
          );
        }}
      </FormList>
    );
  };
  return (
    <Spin spinning={state.loading}>
      <Form
        ref={formRef}
        {...formItemLayout}
        initialValues={{
          methods: [serviceContentDefaultValue],
        }}
        onFinish={onFinish}
      >
        <h3>基本信息</h3>
        <FormItem
          label="服务名称"
          name="serviceName"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '请输入服务名称',
            },
          ]}
        >
          <Input placeholder="请输入服务名称" maxLength={50} />
        </FormItem>
        <FormItem
          label="服务ID"
          name="serviceId"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '请输入服务ID',
            },
          ]}
        >
          <Input placeholder="请输入服务ID" maxLength={50} />
        </FormItem>
        <FormItem
          label="服务描述"
          name="desc"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '请输入服务描述',
            },
          ]}
        >
          <Input placeholder="请输入服务描述" maxLength={50} />
        </FormItem>
        <FormItem
          label="服务命名空间"
          name="nameSpace"
          rules={[
            {
              whitespace: true,
              message: '请输入服务命名空间',
            },
          ]}
        >
          <Input placeholder="请输入服务命名空间" maxLength={50} />
        </FormItem>

        <FormList name={'methods'}>
          {/* FormList嵌套Table时，Table的dataSource来源于FormList的fields */}
          {(fields, { remove, add }) => {
            return (
              <>
                <div>
                  <h3>
                    接口配置
                    <Button
                      style={{ marginLeft: 20 }}
                      type="primary"
                      onClick={() => add(serviceContentDefaultValue)}
                    >
                      新增接口
                    </Button>
                  </h3>
                </div>
                <Table
                  className="add-server-table"
                  size="small"
                  rowKey="key"
                  columns={getCloumns({ remove, add }, fields)}
                  dataSource={fields}
                  pagination={false}
                  expandable={{
                    expandedRowRender: childTableRender,
                    expandIcon: props => {
                      const { expanded, onExpand, record } = props;
                      return (
                        <DownOutlined
                          onClick={e => onExpand(record, e)}
                          rotate={expanded ? 180 : 0}
                          onPointerEnterCapture={() => {}}
                          onPointerLeaveCapture={() => {}}
                        />
                      );
                    },
                  }}
                />
              </>
            );
          }}
        </FormList>
        <FormItem wrapperCol={{ style: { alignItems: 'center', margin: 20 }, span: 24 }}>
          <Button
            type="ghost"
            onClick={() => {
              history.push('/soaManage/serviceManage/serviceLibrary?tab=0');
            }}
          >
            取消
          </Button>
          <Button
            style={{ marginLeft: 20 }}
            type="primary"
            htmlType="submit"
            onClick={() => {
              console.log(
                '🚀 ~ formRef.current?.getFieldsValue():',
                formRef.current?.getFieldsValue(),
              );
            }}
          >
            保存
          </Button>
        </FormItem>
      </Form>
    </Spin>
  );
};
export default connect((state: any) => ({
  basicService: state.basicService,
}))(addServer);
